﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Omu.ValueInjecter;
using LL.Utility.WindowsForms;

namespace NanoERP.Infrastructure
{
    /// <summary>
    /// 绑定单条数据的数据窗体
    /// </summary>
    public partial class EditFormBase : FormBase
    {
        private bool _isSaved;
        public bool IsSaved
        {
            get { return _isSaved; }
            set
            {
                _isSaved = value;
                if (value)
                    this.DialogResult = DialogResult.OK;
            }
        }

        public FormMode Mode { get; set; }
        public Guid Id { get; set; }

        public EditFormBase()
        {
            InitializeComponent();
            if (DesignMode)
                return;
            InitControlers();
            InitializeMembers();
        }

        private void InitControlers()
        {
            this.btnOk.Click += (x, y) =>
            {
                //验证、保存（含对话框）、关闭
                if (Validate() && (IsSaved = DoSaveData()))
                    Close();
            };
        }
        private void InitializeMembers()
        {
            IsSaved = false;
        }
        private bool DoSaveData()
        {
            bool res = SaveData();
            if (res)
                MessageDialogHelper.ShowInfomation("保存成功");
            return res;
        }

        protected virtual void LoadData()
        {
            if (DesignMode)
                return;
            throw new NotImplementedException(
                string.Format("请在{0}类中重写LoadData方法", this.GetType().FullName));
        }

        protected virtual bool SaveData()
        {
            throw new NotImplementedException(
               string.Format("请在{0}类中重写SaveData方法", this.GetType().FullName));
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            if (IsSaved)
                return;
            switch (MessageDialogHelper.ConfirmYesNoCancel("是否保存？"))
            {
                case DialogResult.Cancel:
                    e.Cancel = true;
                    break;

                case DialogResult.Yes:
                    e.Cancel = !DoSaveData();
                    break;
            }
        }

        protected override void OnEnabledChanged(EventArgs e)
        {
            base.OnEnabledChanged(e);
            panel1.Visible = this.Enabled;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            LoadData();
        }

        public enum FormMode
        {
            View,
            Edit,
            Add
        }
    }
}
